package com.raft.framework.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class AssetUtils {

  public static void copy(Context context, String assetName, File dest) {
    AssetManager assetManager = context.getAssets();

    InputStream in = null;
    FileOutputStream out = null;
    try {
      in = assetManager.open(assetName);
      out = new FileOutputStream(dest);

      byte[] buffer = new byte[1024 * 32];
      int read=-1;
      while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
      }

      out.flush();
      out.getFD().sync();
    } catch (IOException e) {
      Log.e("tag", "Failed to copy asset file: " + assetName, e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          //
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          //
        }
      }
    }

  }


  public static @Nullable String read2String(Context context, String assetName){
    AssetManager assetManager = context.getAssets();

    InputStream in = null;
    try {
      in = assetManager.open(assetName);

      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      byte[] buffer = new byte[1024];
      int read=-1;
      while ((read = in.read(buffer)) != -1) {
        baos.write(buffer, 0, read);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e("tag", "Failed to copy asset file: " + assetName, e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          //
        }
      }
    }
    return null;
  }

}
